package com.gitee.qdbp.general.common.biz.files.service.wantu;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.media.MediaConfiguration;
import com.alibaba.media.Result;
import com.alibaba.media.manage.impl.DefaultManageClient;
import com.alibaba.media.utils.DateUtils;
import libs.httpclient.org.apache.http.client.methods.HttpPost;

// DefaultManageClient未提供rename接口
public class SimpleManageClient extends DefaultManageClient {

    public SimpleManageClient(MediaConfiguration configuration) {
        super(configuration);
    }

    // 3.7 重命名文件
    // POST /3.0/files/{resourceId}/rename/{newResourceId}
    public Result<Void> rename(String filePath, String newFilePath) {
        String resourceId = buildResourceId(filePath);
        String newResourceId = buildResourceId(newFilePath);
        String apiVersion = MediaConfiguration.MANAGE_API_VERSION;
        String uri = "/" + apiVersion + "/files/" + resourceId + "/rename/" + newResourceId;
        Map<String, String> params = new HashMap<String, String>();
        Date date = new Date();

        HttpPost rename = new HttpPost(getApiUrl(uri));
        rename.addHeader("Date", DateUtils.formatRfc822Date(date));
        rename.addHeader("Authorization", getAuthorization(uri, date, params));
        rename.addHeader("User-Agent", getUserAgent());

        Result<?> r = execute(rename, null);
        if (r.isSuccess()) {
            return Result.create(r.getHttpStatus(), null);
        } else {
            if ("ResourceNotFound".equals(r.getCode())) {
                return Result.create(r.getHttpStatus(), null);
            }
            return Result.create(r.getHttpStatus(), r.getRequestId(), r.getCode(), r.getMessage());
        }
    }

    protected String getApiUrl(String uri) {
        return MediaConfiguration.MANAGE_ENDPOINT + uri;
    }

    protected String getUserAgent() {
        return "ALIMEDIASDK_JAVA_TAE/" + MediaConfiguration.SDK_VERSION;
    }

    protected String buildResourceId(String filePath) {
        String dir;
        String name;
        int index = filePath.lastIndexOf('/');
        if (index < 0) {
            dir = "/";
            name = filePath;
        } else if (index == 0) {
            dir = "/";
            name = filePath.substring(index + 1);
        } else {
            dir = filePath.substring(0, index);
            name = filePath.substring(index + 1);
        }
        if (!dir.startsWith("/")) {
            dir = "/" + dir;
        }
        return buildResourceId(dir, name);
    }
}
